<?php

namespace app\admin\service;

use app\common\exception\AdminApiException;
use app\common\exception\DbDefaultException;
use app\common\service\BaseService;
use ba\Random;
use think\facade\Db;
use Throwable;

class SiteAdminService extends BaseService
{



    public function __construct()
    {
        parent::__construct();
        $this->model = new \app\admin\model\Admin();
    }


    /**
     * 添加一个 管理员
     * @param $site_id
     * @param $username
     * @param $password
     * @param $nickname
     * @param $mobile
     * @param $auth_rules
     * @param $is_site_admin
     * @return true
     */
    public function addAmin($site_id, $username, $password,$nickname, $mobile, $auth_rules,$is_site_admin = 0)
    {

        $salt   = Random::build('alnum', 16);
        $passwd = encrypt_password($password, $salt);
        $result = false;
        $this->model->startTrans();
        try {
            $data = [
                'site_id'  => $site_id,
                'username' => $username,
                'nickname' => $nickname,
                'password' => $passwd,
                'salt'     => $salt,
                'mobile'   => $mobile,
                'is_site_admin' => $is_site_admin,
            ];
            $result           = $this->model->save($data);

            //开始添加权限组
            $group_id = Db::name('admin_group')->insert([
                'site_id' => $site_id,
                'name' => '超级管理组',
                'rules' => is_array($auth_rules) ? implode(',', $auth_rules) : $auth_rules,
                'create_time' => time(),
                'update_time' => time()
            ],true);

            //添加管理员到权限组
            Db::name('admin_group_access')->insert([
                'uid' => $this->model->id,
                'site_id' => $site_id,
                'group_id' => $group_id
            ]);

            $this->model->commit();
        }catch (Throwable $e){
            $this->model->rollback();
            throw new DbDefaultException($e->getMessage());
        }

        if (!$result) {
            throw new AdminApiException('添加管理员失败');
        }
        return true;

    }



}